<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="包装执行组织" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="organizationCode">
              <el-tree
                ref="tree"
                class="filter-tree"
                show-checkbox
                :data="deptData"
                node-key="orgCode"
                :props="defaultProps"
                :filter-node-method="filterNode"
                :check-strictly="true"
                @check="handleCheck"
                :default-expand-all="true"
                style="max-height: 300px; overflow-y: auto;"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'ErpPackageExecutionOrganizationForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
         },
        defaultProps: {
          children: 'children',
          label: 'title',
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          organizationCode: [
              { required: true, message: '包装执行组织不能为空!'},
          ],
        },
        url: {
          add: "/packageexecutionorganization/erpPackageExecutionOrganization/add",
          edit: "/packageexecutionorganization/erpPackageExecutionOrganization/edit",
          queryById: "/packageexecutionorganization/erpPackageExecutionOrganization/queryById",
          dept: '/sys/sysDepart/queryTreeList',
          checkUnique: "/packageexecutionorganization/erpPackageExecutionOrganization/checkUnique",
        },
        // 部门树下拉
        deptData: [],
        // 车间类型字典
        filteredWorkshopTypeOptions: [],
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      this.getDeptData();
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    mounted() {
    },
    methods: {
      // 部门下拉数据
      getDeptData() {
        getAction(this.url.dept).then(res => {
            this.deptData=res.result
            // 树数据加载完成后检查是否需要选中节点
            if (this.model.organizationCode) {
              this.$nextTick(() => {
                this.setSelectedNode();
              });
            }
          }).catch(e=>{
            this.$emit(e);
          })
      },
      // 设置选中节点
      setSelectedNode() {
        if (this.$refs.tree && this.model.organizationCode) {
          // 设置选中节点
          this.$refs.tree.setCheckedKeys([this.model.organizationCode]);
          // 展开到选中节点
          const node = this.$refs.tree.getNode(this.model.organizationCode);
          if (node) {
            // 使用 expandParent 方法展开父节点
            this.expandParent(node);
          }
        }
      },
      // 递归展开父节点
      expandParent(node) {
        if (node.parent) {
          this.expandParent(node.parent);
          node.expanded = true;
        }
      },
      filterNode(value, data) {
        if (!value) return true
        return data.title.indexOf(value) !== -1
      },
      handleCheck(currentNode, checkStatus) {
        // 获取当前选中的节点ID数组
        const checkedKeys = checkStatus.checkedKeys;
        // 确保单选：只保留最后一个选中的节点
        if (checkedKeys.length > 1) {
          // 获取最后一个选中的节点ID
          // const lastKey = checkedKeys[checkedKeys.length - 1];
          const lastKey = currentNode.orgCode;
          // 设置只选中最后一个节点
          this.$refs.tree.setCheckedKeys([lastKey]);
          this.model.organizationCode = lastKey;
          this.model.organizationName = currentNode.departName;
        } else if (checkedKeys.length === 1) {
          // 正常选中一个节点
          this.model.organizationCode = currentNode.orgCode;
          this.model.organizationName = currentNode.departName;
        } else {
          // 没有选中任何节点
          this.model.organizationCode = '';
          this.model.organizationName = '';
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit(record) {
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.setSelectedNode();
        });
      },
      submitForm () {
        const that = this;
        if (this.model.organizationCode === '' || this.model.organizationCode === null || this.model.organizationCode === undefined) {
            this.$message.warning('请选择包装执行组织')
            return
        }
        // 校验组织是否已经存在
        let params = {
          departCode: this.model.organizationCode,
          id: this.model.id
        }
        getAction(this.url.checkUnique, params).then(res => {
          if(res.success){
            if(res.result){
              this.$message.warning('该包装执行组织已存在！')
                return
            }else {
              // 触发表单验证
              this.$refs.form.validate(valid => {
                if (valid) {
                  that.confirmLoading = true;
                  let httpurl = '';
                  let method = '';
                  if(!this.model.id){
                    httpurl+=this.url.add;
                    method = 'post';
                  }else{
                    httpurl+=this.url.edit;
                    method = 'put';
                  }
                  httpAction(httpurl,this.model,method).then((res)=>{
                    if(res.success){
                      that.$message.success(res.message);
                      that.$emit('ok');
                    }else{
                      that.$message.warning(res.message);
                    }
                  }).finally(() => {
                    that.confirmLoading = false;
                  })
                }
              })
            }
          }
        }).catch(e=>{
          this.$emit(e);
        })
      },
    }
  }
</script>